package com.swpu.service_comsumer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.swpu.service_comsumer.utils.SmsSender;
import com.swpu.service_comsumer.utils.WxConfigProperties;
import com.swpu.service_drink.service.DrinkRecordService;
import com.swpu.service_remind.WeChatSubscribeMessageSender;
import com.swpu.service_remind.WxCommonService;
import com.swpu.service_remind.config.RabbitExChangeConfig;
import com.swpu.service_remind.entity.Medicine;
import com.swpu.service_remind.service.MedicineRemindService;
import com.swpu.service_user.entity.User;
import com.swpu.service_user.service.UserService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DeadQueueListener {

    @Autowired
    private WxCommonService wxCommonService;
    @Autowired
    private DrinkRecordService drinkRecordService;
    @Autowired
    private MedicineRemindService medicineRemindService;
    @Autowired
    private UserService userService;


    @RabbitListener(queues = RabbitExChangeConfig.DEAD_LETTER_QUEUE)
    public void receive(Message message, Channel channel) throws IOException {
        System.out.println("收到死信消息A：" + new String(message.getBody()));
        JSONObject jsonObject = JSONObject.parseObject(new String(message.getBody()));
        String messageType = jsonObject.getString("messageType");
        //当前通知为饮水提醒
        if (messageType.equals("1")) {
            this.sendDrinkRemindMessages(jsonObject);
        } else if (messageType.equals("2")) {
            this.sendMedicineRemindMessages(jsonObject);
        } else if (messageType.equals("3")) {
            this.sendSitRemindMessages(jsonObject);
        } else if (messageType.equals("4")) {
            this.sendCheckupRemindMessages(jsonObject);
        }
        //确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    private void sendCheckupRemindMessages(JSONObject jsonObject) {
        String openid = jsonObject.getString("userId");
        String date = jsonObject.getString("date");
        DateTime dateTime = DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss");
        Integer enableWx = jsonObject.getInteger("enableWx");
        Integer enableSms = jsonObject.getInteger("enableSms");
        User user = userService.getUserInfo(openid);
        //用户开启了微信提醒
        if (enableWx == 1) {
            String accessToken = wxCommonService.refreshAccessToken(WxConfigProperties.APP_ID, WxConfigProperties.APP_SECRET);
            if (accessToken == null) {
                throw new RuntimeException("未获取到access_token");
            }
            // 构建订阅消息内容的JSON对象
            JSONObject messageData = new JSONObject();
            messageData.put("thing1", createDataItem("温馨提醒", "今天是您体检的日子，别忘记了哟"));
            messageData.put("time2", createDataItem("当前时间", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm")));
            // 将订阅消息内容转换为JSON字符串
            String jsonData = messageData.toJSONString();
            //发送微信小程序通知
            WeChatSubscribeMessageSender.sendSubscribeMessage(accessToken, openid, WxConfigProperties.COMMON_REMIND_FORM_ID, null, jsonData);
        }
        if (enableSms == 1) {
            SmsSender.sendSms(user.getPhone(), "体检通知", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm"));
       //     System.out.println("短信发送成功");
        }
    }

    public void sendDrinkRemindMessages(JSONObject jsonObject) {
        String openid = jsonObject.getString("userId");
        String date = jsonObject.getString("date");
        DateTime dateTime = DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss");
        Integer enableWx = jsonObject.getInteger("enableWx");
        Integer enableSms = jsonObject.getInteger("enableSms");
        User user = userService.getUserInfo(openid);
        //用户开启了微信提醒
        if (enableWx == 1) {
            String accessToken = wxCommonService.refreshAccessToken(WxConfigProperties.APP_ID, WxConfigProperties.APP_SECRET);
            if (accessToken == null) {
                throw new RuntimeException("未获取到access_token");
            }
            //获取用户当日饮水信息
            Integer volume = (Integer) drinkRecordService.getDrinkVolumeByDate(openid, dateTime).get("todayVolume");
            Integer drinkTarget = user.getDrinkTarget();
            // 构建订阅消息内容的JSON对象
            JSONObject messageData = new JSONObject();
            messageData.put("thing1", createDataItem("温馨提醒", "到饮水时间啦"));
            messageData.put("character_string3", createDataItem("当前饮水量", volume + "ml"));
            messageData.put("thing5", createDataItem("目标饮水量", drinkTarget + "ml"));
            messageData.put("time6", createDataItem("饮水时间", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm")));
            // 将订阅消息内容转换为JSON字符串
            String jsonData = messageData.toJSONString();
            //发送微信小程序通知
            WeChatSubscribeMessageSender.sendSubscribeMessage(accessToken, openid, WxConfigProperties.DRINK_REMIND_FORM_ID, null, jsonData);
        }
        if (enableSms == 1) {
            SmsSender.sendSms(user.getPhone(), "饮水提醒", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm"));
            System.out.println("短信发送成功");
        }
    }

    public void sendSitRemindMessages(JSONObject jsonObject) {
        String openid = jsonObject.getString("userId");
        String date = jsonObject.getString("date");
        DateTime dateTime = DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss");
        Integer enableWx = jsonObject.getInteger("enableWx");
        Integer enableSms = jsonObject.getInteger("enableSms");
        User user = userService.getUserInfo(openid);
        System.out.println(enableSms + "^^^^^^");
        //用户开启了微信提醒
        if (enableWx == 1) {
            String accessToken = wxCommonService.refreshAccessToken(WxConfigProperties.APP_ID, WxConfigProperties.APP_SECRET);
            if (accessToken == null) {
                throw new RuntimeException("未获取到access_token");
            }
            // 构建订阅消息内容的JSON对象
            JSONObject messageData = new JSONObject();
            messageData.put("thing1", createDataItem("温馨提醒", "您已经坐很久啦，快去放松休息会儿吧!"));
            messageData.put("time2", createDataItem("当前时间", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm")));
            // 将订阅消息内容转换为JSON字符串
            String jsonData = messageData.toJSONString();
            //发送微信小程序通知
            WeChatSubscribeMessageSender.sendSubscribeMessage(accessToken, openid, WxConfigProperties.COMMON_REMIND_FORM_ID, null, jsonData);
        }
        if (enableSms == 1) {
            SmsSender.sendSms(user.getPhone(), "久坐提醒", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm"));
            System.out.println("短信发送成功");
        }
    }

    public void sendMedicineRemindMessages(JSONObject jsonObject) {
        String messageType = jsonObject.getString("messageType");
        String openid = jsonObject.getString("userId");
        String date = jsonObject.getString("date");
        DateTime dateTime = DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss");
        Integer enableWx = jsonObject.getInteger("enableWx");
        Integer enableSms = jsonObject.getInteger("enableSms");
        String medicineRemindId = jsonObject.getString("medicineRemindId");
        User user = userService.getUserInfo(openid);
        //用户开启了微信提醒
        if (enableWx == 1) {
            String accessToken = wxCommonService.refreshAccessToken(WxConfigProperties.APP_ID, WxConfigProperties.APP_SECRET);
            if (accessToken == null) {
                throw new RuntimeException("未获取到access_token");
            }
            //获取用户吃药提醒信息
            //     MedicineRemindVo medicineRemind = medicineRemindService.getMedicineRemindById(openid,medicineRemindId);
            List<Medicine> medicines = medicineRemindService.getMedicinesById(medicineRemindId);
            String medicineNames = "";
            String medicineInfo = "";
            for (Medicine medicine : medicines) {
                medicineNames += medicine.getMedicineName() + " ";
                medicineInfo += medicine.getMedicineName() + ": (" + medicine.getMedicineDose() + ")";
            }
            // 构建订阅消息内容的JSON对象
            JSONObject messageData = new JSONObject();
            messageData.put("thing4", createDataItem("温馨提醒", "到吃药时间啦"));
            messageData.put("thing1", createDataItem("药品", medicineNames));
            messageData.put("thing3", createDataItem("剂量", medicineInfo));
            messageData.put("time15", createDataItem("提醒时间", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm")));
            // 将订阅消息内容转换为JSON字符串
            String jsonData = messageData.toJSONString();
            //发送微信小程序通知
            WeChatSubscribeMessageSender.sendSubscribeMessage(accessToken, openid, WxConfigProperties.MEDICINE_REMIND_FORM_ID, null, jsonData);
        }
        if (enableSms == 1) {
            SmsSender.sendSms(user.getPhone(), "吃药提醒", DateUtil.format(dateTime, "yyyy年MM月dd日 HH:mm"));
            System.out.println("短信发送成功");
        }
    }

    private static Map<String, Object> createDataItem(String name, String value) {
        Map<String, Object> item = new HashMap<>();
        item.put("value", value);
        return item;
    }
}
